from odoo import fields, models, api
from odoo.exceptions import UserError
from odoo.addons.rp_courier_management.models.primary.rp_courier_mail_route import FULFILLMENT_TYPE


class RPAvailableShipperFulfillmentTran(models.TransientModel):
    _name = 'rp.available.shipper.fulfillment.tran'
    _description = "可用头尾程"
    _rec_name = 'rp_asff_code'

    def _default_auto_rp_asff_code(self):
        records = self.env['rp.available.shipper.fulfillment.tran'].search([])
        return "RP_ASFF" + str(len(records) + 1).zfill(3)

    rp_asff_code = fields.Char(string='索引码', default=_default_auto_rp_asff_code, index=True, copy=False, readonly=True)
    rp_ship_order_id = fields.Many2one(string='关联订单', comodel_name='rp.ship.order', ondelete='cascade')
    currency_id = fields.Many2one(string='货币单位', comodel_name='res.currency', default=lambda self: self.env.company.currency_id)

    operation_name = fields.Char(string='名称', readonly=True)
    operation_type = fields.Selection(string='类型', selection=FULFILLMENT_TYPE, readonly=True)
    available_flag = fields.Boolean(string='可用', readonly=False)

    tag_price = fields.Float(string='标价', digits=(8, 3), default=0)
    sale_adjusted_price = fields.Float(string='销售调后价', digits=(8, 3), default=0)

    used_sale_price_adjust_ids = fields.Many2many(string='使用销售调价', comodel_name='rp.shipper.sale.price.adjustment', readonly=True,
                                                  relation='rp_asff_and_sale_price_adjustment_rel', column1='asff_id', column2='sale_price_adjustment_id')

    def action_rewrite_first_mile(self):
        """ 写入头程数据 """
        record = self.browse(self.env.context.get('active_ids'))
        if len(record) > 1:
            raise UserError('只能选择一条记录')
        if record.operation_type not in [FULFILLMENT_TYPE[0][0], FULFILLMENT_TYPE[1][0]]:
            raise UserError('头程只能选择“网点收件”或者“上门取件”')
        if not record.available_flag:
            raise UserError('当前头尾程不可用')
        ship_order = self.env['rp.ship.order'].browse(self.env.context.get('ship_order_id'))

        # 1、如果原单据已经有头程数据，则清空
        original_first_mile = ship_order.rp_ship_order_fulfillment_line_ids.filtered(lambda i: i.operation_type in [FULFILLMENT_TYPE[0][0], FULFILLMENT_TYPE[1][0]])
        original_value_added = ship_order.rp_ship_order_value_added_line_ids.filtered(lambda i: i.value_added_id.name in [FULFILLMENT_TYPE[0][0], FULFILLMENT_TYPE[1][0]])
        if original_first_mile:
            ship_order.write({'rp_ship_order_fulfillment_line_ids': [(2, original_first_mile.id)],
                              'rp_ship_order_value_added_line_ids': [(2, original_value_added.id)]})

        # 2、获取该头尾程的增值服务
        value_added = self.env['rp.value.added.service'].search([('name', '=', str(record.operation_type))])

        # 3、写入新的头程数据
        ship_order.write({'rp_ship_order_fulfillment_line_ids': [(0, 0, {'rp_ship_order_id': ship_order.id,
                                                                         'name': record.operation_name,
                                                                         'operation_type': record.operation_type,
                                                                         'available_flag': record.available_flag,
                                                                         'use_flag': True})],
                          'rp_ship_order_value_added_line_ids': [(0, 0, {'rp_ship_order_id': ship_order.id,
                                                                         'value_added_id': value_added.id,
                                                                         'value_added_type': value_added.type,
                                                                         'tag_price': record.tag_price,
                                                                         'sale_adjusted_price': record.sale_adjusted_price,
                                                                         'used_sale_price_adjust_ids': [(6, 0, record.used_sale_price_adjust_ids.ids)], })]})

    def action_rewrite_last_mile(self):
        """ 写入尾程数据 """
        record = self.browse(self.env.context.get('active_ids'))
        if len(record) > 1:
            raise UserError('只能选择一条记录')
        if record.operation_type not in [FULFILLMENT_TYPE[2][0], FULFILLMENT_TYPE[3][0]]:
            raise UserError('尾程只能选择“网点取件”或者“送货上门”')
        if not record.available_flag:
            raise UserError('当前头尾程不可用')
        ship_order = self.env['rp.ship.order'].browse(self.env.context.get('ship_order_id'))

        # 1、如果原单据已经有头程数据，则清空
        original_first_mile = ship_order.rp_ship_order_fulfillment_line_ids.filtered(lambda i: i.operation_type in [FULFILLMENT_TYPE[2][0], FULFILLMENT_TYPE[3][0]])
        original_value_added = ship_order.rp_ship_order_value_added_line_ids.filtered(lambda i: i.value_added_id.name in [FULFILLMENT_TYPE[2][0], FULFILLMENT_TYPE[3][0]])
        if original_first_mile:
            ship_order.write({'rp_ship_order_fulfillment_line_ids': [(2, original_first_mile.id)],
                              'rp_ship_order_value_added_line_ids': [(2, original_value_added.id)]})

        # 2、获取该头尾程的增值服务
        value_added = self.env['rp.value.added.service'].search([('name', '=', str(record.operation_type))])

        # 3、写入新的尾程数据
        ship_order.write({'rp_ship_order_fulfillment_line_ids': [(0, 0, {'rp_ship_order_id': ship_order.id,
                                                                         'name': record.operation_name,
                                                                         'operation_type': record.operation_type,
                                                                         'available_flag': record.available_flag,
                                                                         'use_flag': True})],
                          'rp_ship_order_value_added_line_ids': [(0, 0, {'rp_ship_order_id': ship_order.id,
                                                                         'value_added_id': value_added.id,
                                                                         'value_added_type': value_added.type,
                                                                         'tag_price': record.tag_price,
                                                                         'sale_adjusted_price': record.sale_adjusted_price,
                                                                         'used_sale_price_adjust_ids': [(6, 0, record.used_sale_price_adjust_ids.ids)], })]})
